package com.zzj.ecology.common.utils;

import com.zzj.ecology.common.config.Audience;
import io.jsonwebtoken.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Base64Utils;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Date;

public class JWTUtils {

    private static Logger logger = LoggerFactory.getLogger(JWTUtils.class);
    private static final String SECRET = "$2a$10$CIG6HIZ42nCak4LVilJmIe9l5hdMly9txq6y9D2cotP7K.sLIX0Km";//welcome use tgf
    public static long EXPIRE = 7 * 24 * 3600 * 1000;// 毫秒数.过期时间7天

    public static final String LOGIN_NAME_KEY = "username";
    public static final String TOKEN_KEY = "token";

    /**
     * 生成jwt token
     */
    public static String buildToken(long userId, String username) {
        Date nowDate = new Date();
        //过期时间
        Date expireDate = new Date(nowDate.getTime() + EXPIRE);
        String usernameBase64 = Base64Utils.encodeToString(username.getBytes());
        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setSubject(usernameBase64)
                .claim(LOGIN_NAME_KEY, username)
                .claim("userId", userId)
                .setIssuedAt(nowDate)
                .setExpiration(expireDate)
                .signWith(SignatureAlgorithm.HS512, SECRET)
                .compact();
    }

    public static Claims obtainClaimsByToken(String token) {
        try {
            return Jwts.parser()
                    .setSigningKey(SECRET)
                    .parseClaimsJws(token)
                    .getBody();
        } catch (Exception e) {
            logger.debug("validate is token error ", e);
            return null;
        }
    }

    /**
     * 获取登录用户
     * @param token
     * @return
     */
    public static String getLoginName(String token) {
        return (String) obtainClaimsByToken(token).get(LOGIN_NAME_KEY);
    }

    /**
     * token是否过期
     *
     * @return true：过期
     */
    public static boolean isTokenExpired(String token) {
        return obtainClaimsByToken(token).getExpiration().before(new Date());
    }

    public String getKey() {
        return SECRET;
    }

}
